<template>
  <ContentCard>
    <PageHeaderNew
      :title="`${releaseApprovalData.approvalTitle}`"
      :breadCrumb="breadCrumb"
      showBack
    />
    <div class="stemp-index">
      <template v-for="item in formInfo" :key="item.id">
        <template v-if="item.componentType === 'CONTAINER'">
          <div>
            <div class="sub-name">{{ item.cnName }}</div>
            <div style="padding: 0 20px">
              <RenderingForm
                :set-up-list="item.controlDetailList"
                :layout="rest"
                :regex="regex"
                :review="true"
                :field-names="{
                  labelName: 'cnName',
                  componentType: 'componentType'
                }"
                ref="renderFormRef"
              />
            </div>
          </div>
        </template>
        <template v-else>
          <RenderingForm
            :set-up-list="[item]"
            :layout="rest"
            :regex="regex"
            :review="true"
            :field-names="{
              labelName: 'cnName',
              componentType: 'componentType'
            }"
            ref="renderFormRef"
          />
        </template>
      </template>

      <a-steps v-if="isFull" :current="-1" type="dot" :direction="'vertical'">
        <template v-for="(item, pointIndex) in approvalTree" :key="item.id">
          <a-step v-if="![4, 5, 6].includes(Number(item.pointType))">
            {{ item.pointName }}
            <template #description>
              <div class="point-detail">
                <div class="point-description">{{ item.pointName }}</div>
                <div class="ponit-operation">
                  <a-space :align="'start'">
                    <a-space
                      v-for="(user, userIndex) in item.participantList"
                      :key="user.objId"
                      :direction="'vertical'"
                      style="align-items: center"
                    >
                      <a-avatar
                        :style="{ backgroundColor: '#3370ff' }"
                        :size="32"
                        shape="square"
                        :trigger-icon-style="{
                          width: '16px',
                          height: '16px',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          background: '#eee'
                        }"
                      >
                        <IconUser />
                        <template
                          v-if="item.participantFormat === 2"
                          #trigger-icon
                        >
                          <icon-close
                            :size="12"
                            @click="del(pointIndex, userIndex)"
                          />
                        </template>
                      </a-avatar>
                      <div>{{ user.objName }}</div>
                    </a-space>
                    <a-button
                      v-if="item.participantFormat === 2"
                      :type="'outline'"
                      @click="item.visible = true"
                    >
                      <template #icon>
                        <icon-plus />
                      </template>
                    </a-button>
                    <PersonnelSelectionModal
                      v-model:visible="item.visible"
                      v-model:participantInfos="item.participantInfos"
                    />
                  </a-space>
                </div>
              </div>
            </template>
          </a-step>
        </template>
      </a-steps>
      <a-space
        class="wrapper"
        direction="vertical"
        fill
        style="align-items: center"
      >
        <a-button type="primary" style="width: 230px" long @click="submit"
          >提交</a-button
        >
      </a-space>
    </div>
  </ContentCard>
</template>
<script setup lang="ts">
import {
  addApprovalRelease,
  getFlowPanelPointList,
  getFlowCtlList,
  getFlowById
} from '@/apis/approve/index';
import { useRoute, useRouter } from 'vue-router';
import RenderingForm from '@/components/DyForms/DynamicForms/RenderingForm/Form/index.vue';
import regex from '@/utils/regex';
import type {
  ApprovalRelease,
  PointDetail,
  Participant,
  CtlValueInfo
} from '@/apis/approve/type';
import { localGetUserInfo } from '@/utils/localStorage/account';
import { GetHumanRosterDetail } from '@/apis/humanRoster/index';
import { cloneDeep } from 'lodash';
import ContentCard from '@/components/ContentCard/index.vue';

const route = useRoute();
const router = useRouter();

const breadCrumb: string[] = ['人事', '人事管理', '入职审批'];
const routeQuery = reactive({ userId: 0, processId: 0 });
const userInfo = localGetUserInfo();
const init = async () => {
  routeQuery.userId = Number(route.query.userId);
  routeQuery.processId = Number(route.query.processId);
  if (!routeQuery.userId) return;
  if (!routeQuery.processId) return;
  releaseApprovalData.value.processId = routeQuery.processId;
  //TODO:改成promise.all
  await getUserCtlInfo();
  await getCtl();
  await getProcess();
  await getFlowInfo();
};
const rest = ref('horizontal');
onMounted(() => {
  init();
});

/**
 * 获取流程信息
 */
const getFlowInfo = async () => {
  const res = await getFlowById(routeQuery.processId);
  const { addSignature, flowName } = res.processInfo;
  releaseApprovalData.value.addSignature = addSignature;
  const { name } = userInfo;
  releaseApprovalData.value.approvalTitle = `${name}发起的${flowName}`;
};
const formInfo = ref<any>();
const setUpList = ref<any[]>([]); // 审批的控件列表
// 获取流程的控件
const getCtl = async () => {
  const res = await getFlowCtlList(routeQuery.processId);
  if (!res || !res.formInfo) return;
  const { controlDetailList, subsetDetailList } = res.formInfo;
  subsetDetailList?.forEach((item) => {
    item.props = JSON.parse(item.props);
    item.componentType = 'CONTAINER';
    item?.controlDetailList?.forEach((ctl) => {
      ctl.props = JSON.parse(ctl.props);
      ctl.values = ctl.values?.length ? JSON.parse(ctl.values) : void 0;
    });
  });
  controlDetailList?.forEach((item) => {
    item.props = JSON.parse(item.props);
    item.values?.length ? JSON.parse(item.values) : void 0;
    item?.childrenCtl?.forEach((chi) => {
      chi.props = JSON.parse(chi.props);
    });
  });
  // console.log("subsetDetailList", subsetDetailList);

  formInfo.value = [...(controlDetailList || []), ...(subsetDetailList || [])];
  formInfo.value.sort((a: any, b: any) => a.orderNo - b.orderNo);
  setUpList.value = [...(controlDetailList || [])];
  subsetDetailList?.forEach((item) => {
    const { controlDetailList: controlDetailList2 } = item;
    if (!controlDetailList2?.length) return;
    setUpList.value = [
      ...(setUpList.value || []),
      ...(controlDetailList2 || [])
    ];
  });
  setUpList.value.forEach((item) => {
    if (!controlModel.value?.length) return;
    const ctlItem = controlModel.value.find(
      (ctl) => ctl.ctlCode === item.ctlCode
    );
    if (!ctlItem) return;
    item.values = ctlItem.ctlValue.ctlValue;
  });
};
const controlModel = ref();
/**
 * 获取用户模板控件信息
 */
const getUserCtlInfo = async () => {
  const res = await GetHumanRosterDetail({ id: routeQuery.userId });
  if (!res?.useTemplate?.collectionModel) return;
  const collectionModel = res.useTemplate.collectionModel?.flat();

  controlModel.value = [].concat(
    ...collectionModel.map((item) => item.controlModel)
  );
};
const isFull = ref(true);
watch(
  () => setUpList.value,
  () => {
    //必填项都有值后，根据控件判断显示哪条审批路线
    isFull.value = true;
    // for (const item of setUpList.value) {
    //   if (!item.values && item.required === 1) {
    //     isFull.value = false;
    //     return;
    //   }
    // }
    // if (!isFull.value) return;
    getProcessTree();
  },
  { deep: true }
);
const panelPointList = ref<any[]>([]); // 审批的流程节点列表
const approvalTree = ref<PointDetail[]>([]);
// 获取流程所有节点
const getProcess = async () => {
  const res = await getFlowPanelPointList({ processId: routeQuery.processId });
  panelPointList.value = res.panelPointList || [];
};
const getProcessTree = () => {
  approvalTree.value = [];
  //根据表单获取审批路线
  //找到发起人
  const initiator = panelPointList.value.find((item) => item.pointType === 5);

  if (!initiator) return;
  approvalTree.value.push(initiator);
  gh(initiator);
};
/**
 * 依次根据关系一直寻找下一节点并记录(条件节点外)，直至结束节点
 * @param point 节点详情
 */
const gh = (point: PointDetail) => {
  if (!point || point.pointType === 6) return;
  //next point 判断条件节点线路
  let nextNode: PointDetail = {};
  let isCondition = false;
  const conditionList: any[] = [];
  if (point.relDescDetail[0].nextStepType === 4) {
    point.relDescDetail.forEach((point: any) => {
      const pointItem = panelPointList.value.find(
        (item) => item.id === point.nextStep
      );
      conditionList.push(pointItem);
    });
    conditionList.sort((a: any, b: any) => a.priority - b.priority);
    for (const iterator of conditionList) {
      nextNode = iterator;
      if (!nextNode.groupsDetailList?.length) {
        break;
      }
      for (const group of nextNode.groupsDetailList) {
        let flag = true; //条件是否全部符合要求
        for (const condition of group.conditionItemsList) {
          const {
            ctlId,
            comparatorType,
            comparatorOne,
            comparatorTwo,
            compareValueOne,
            compareValueTwo
          } = condition;
          const ctlItem = setUpList.value.find((ctl) => ctl.id === ctlId);
          const ctlValue = Number(ctlItem?.values);
          const valueOne = Number(compareValueOne);
          const valueTwo = Number(compareValueTwo);
          if (comparatorType === 5) {
            if (comparatorOne === 1 && ctlValue <= valueOne) {
              flag = false;
              break;
            }
            if (comparatorOne === 2 && ctlValue < valueOne) {
              flag = false;
              break;
            }
            if (comparatorTwo === 1 && ctlValue >= valueTwo) {
              flag = false;
              break;
            }
            if (comparatorTwo === 2 && ctlValue > valueTwo) {
              flag = false;
              break;
            }
          } else {
            if (comparatorType === 1 && ctlValue <= valueOne) {
              flag = false;
              break;
            }
            if (comparatorType === 2 && ctlValue >= valueOne) {
              flag = false;
              break;
            }
            if (comparatorType === 3 && ctlValue < valueOne) {
              flag = false;
              break;
            }
            if (comparatorType === 4 && ctlValue > valueOne) {
              flag = false;
              break;
            }
            if (comparatorType === 6 && ctlValue <= valueOne) {
              flag = false;
              break;
            }
            if (comparatorType === 7 && ctlValue <= valueOne) {
              flag = false;
              break;
            }
          }
        }
        if (flag) {
          isCondition = true;
          break;
        }
      }
      if (isCondition) break;
    }
  } else {
    const nextNodeId = point.relDescDetail[0].nextStep;
    nextNode = panelPointList.value.find((item) => item.id === nextNodeId);
  }
  //条件节点不加入,把nextNode的上节点及类型改成已保存的最后一个节点及类型，最后一个节点的下节点及类型改成nextNode节点及类型
  if (nextNode.pointType !== 4) {
    const lastElement = approvalTree.value.slice(-1)[0];

    const len = approvalTree.value.length;
    approvalTree.value[len - 1].nextStep = nextNode.id;
    approvalTree.value[len - 1].nextStepType = nextNode.pointType;
    nextNode.previousStep = lastElement.id;
    nextNode.previousStepType = lastElement.pointType;
    // console.log('nextNode', nextNode);
    approvalTree.value.push(nextNode);
  }

  gh(nextNode);
};
const releaseApprovalData = ref<ApprovalRelease>({
  appCode: 'APP280373000',
  processId: 0,
  addSignature: 2,
  automaticWeightRemoval: 1,
  approvalTitle: `发起的加班`,
  approvalFormDetail: { approvalCtlValueDetailList: [] },
  pointDetails: []
});
const renderFormRef = ref();
const submit = async () => {
  //验证表单
  // if (renderFormRef.value?.length) {
  //   renderFormRef.value.forEach(async (item, index) => {
  //     const check = await item.validate();
  //   });
  // } else {
  //   renderFormRef.value.validate();
  // }
  // renderFormRef.value.validate();
  // console.log('renderFormRef.value');

  // if (!isFull.value) return;
  releaseApprovalData.value.approvalFormDetail.approvalCtlValueDetailList = [];
  releaseApprovalData.value.approvalFormDetail.approvalSubsetDetailList = [];
  //获取控件的值
  // console.log('formInfo', formInfo.value);
  const copyFormInfo = cloneDeep(formInfo.value);
  copyFormInfo.forEach((item) => {
    if (item.componentType === 'CONTAINER') {
      item.id = void 0;
      item.props = JSON.stringify(item.props);
      item.controlDetailList?.forEach((ctl) => {
        ctl.ctlId = ctl.id;
        ctl.props = JSON.stringify(ctl.props);
        ctl.values = ctl.values?.length ? ctl.values : void 0;
        ctl.values = JSON.stringify(ctl.values);

        ctl.id = void 0;
        ctl.ctlValue = ctl.values;
      });
      const subItem = {
        ...item,
        approvalCtlValueDetailList: item.controlDetailList
      };
      releaseApprovalData.value.approvalFormDetail.approvalSubsetDetailList?.push(
        subItem
      );
    } else {
      item.ctlId = item.id;
      item.props = JSON.stringify(item.props);
      item.id = void 0;
      item.values = item.values?.length ? item.values : void 0;
      item.values = JSON.stringify(item.values);
      item.ctlValue = item.values;
      item?.childrenCtl?.forEach((chi) => {
        chi.id = void 0;
        chi.props = JSON.stringify(chi.props);
        chi.values = chi.values?.length ? chi.values : void 0;
        chi.values = JSON.stringify(chi.values);
      });
      releaseApprovalData.value.approvalFormDetail.approvalCtlValueDetailList?.push(
        item
      );
    }
  });
  releaseApprovalData.value.pointDetails = [];
  //遍历流程节点,去掉条件节点，然后调整条件节点的上下节点
  approvalTree.value.forEach((ele, index) => {
    let obj: PointDetail = {
      pointId: ele.id,
      nextStep: ele.nextStep,
      nextStepType: ele.nextStepType,
      previousStep: ele.previousStep,
      previousStepType: ele.previousStepType,
      pointType: ele.pointType,
      pointName: ele.pointName,
      examineType: ele.examineType,
      participantInfos: []
    };
    if (ele.pointType === 4) return;

    ele.participantList?.forEach((detail: any, userIndex: any) => {
      let user = {
        objId: detail.objId,
        // pointValueId: ele.id,
        orderNo: userIndex + 1,
        objType: 1,
        ownerType: 1,
        objName: detail.objName
      };
      obj.participantInfos?.push(user);
    });
    if (ele.pointType === 5) {
      obj.participantInfos = [
        {
          objId: userInfo.id,
          objName: userInfo.name,
          objType: 1,
          ownerId: ele.id,
          ownerType: 2
        }
      ];
    }
    releaseApprovalData.value.pointDetails?.push(obj);
  });
  // console.log(".value", releaseApprovalData.value);

  await addApprovalRelease(releaseApprovalData.value);
};
const del = (a: any, b: any) => {
  //
};
</script>
<style lang="less" scoped>
.stemp-index {
  // width: 750px;
  // margin: 20px auto;
  // border: 1px solid #eee;
  //   box-shadow: 0 3px 3px #eee;
  padding: 12px;
  .point-detail {
    display: flex;
    .ponit-operation {
      position: absolute;
      right: 0px;
      top: 0px;
      display: flex;
    }
  }
  .sub-name {
    height: 36px;
    border-radius: 4px;
    line-height: 36px;
    font-weight: 700;
    background: #edeffd;
    padding: 5px 16px;
    // font-size: 18px;
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    &::before {
      position: relative;
      // top: 38px;
      // left: 10px;
      display: inline-block;
      height: 20px;
      width: 5px;
      margin-right: 10px;
      border-radius: 2px;
      content: '';
      background-color: #165dff;
    }
  }
}
:deep(.arco-steps-item) {
  margin: 0;
}
:deep(.arco-avatar-trigger-icon-button) {
  top: 0;
  right: 0;
  transform: translate(50%, -25%);
}
.wrapper {
  margin-top: 16px;
}
</style>
